import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

import java.math.BigDecimal; // 确保导入BigDecimal

public class EditGoodsServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        String goods_id = request.getParameter("goods_id");
        String goods_name = request.getParameter("goods_name");
        String category = request.getParameter("category");
        String unitprice = request.getParameter("unitprice");
        String stock = request.getParameter("stock");
        String photo = request.getParameter("photo");
        String details = request.getParameter("details");
        String add_time = request.getParameter("add_time");
        String change_time = request.getParameter("change_time");
        String goods_state = request.getParameter("goods_state");

        String url = "jdbc:mysql://localhost:3306/shop?useSSL=false&serverTimezone=UTC&user=root&password=123456";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            try (Connection connection = DriverManager.getConnection(url)) {
                String sql = "UPDATE goods SET goods_name=?, category=?, unitprice=?, stock=?, photo=?, details=?, add_time=?, change_time=?, goods_state=? WHERE goods_id=?";
                try (PreparedStatement statement = connection.prepareStatement(sql)) {
                    statement.setString(1, goods_name);
                    statement.setString(2, category);
                    statement.setBigDecimal(3, new BigDecimal(unitprice));
                    statement.setInt(4, Integer.parseInt(stock));
                    statement.setString(5, photo);
                    statement.setString(6, details);
                    statement.setDate(7, Date.valueOf(add_time));
                    statement.setDate(8, change_time.equals("") ? null : Date.valueOf(change_time));
                    statement.setInt(9, Integer.parseInt(goods_state));
                    statement.setString(10, goods_id);
                    int rowsAffected = statement.executeUpdate();
                    if (rowsAffected > 0) {
                        response.getWriter().println("<script>alert('商品更新成功！');window.location.href='menu/device/3-1.jsp';</script>");
                    } else {
                        response.getWriter().println("<script>alert('商品更新失败！');window.location.href='menu/device/3-1.jsp';</script>");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println("<script>alert('商品更新过程中发生错误！');window.location.href='menu/device/3-1.jsp';</script>");
        }
    }
}